#!/usr/bin/env python
#coding: utf-8
'''
Created on 2017年4月17日

@author: Administrator
'''

import datetime
import random
import re
import urllib, urllib2
import sys

from django.contrib.auth.models import User
from django.core.mail import EmailMessage as DJEmailMessage, get_connection
from django.template.loader import render_to_string
from django.utils.log import getLogger

from celery.task import task
from message import settings
from message.models import Message, EmailMessage, MobileMessage, ValidateMessage

logger = getLogger('django.request')

def gather_href(url, text):
    """将url和文本拼接成html超链接标签"""
    
    # return u'''<a href="%s" target="_blank"><span class="Eblue">%s</span></a>''' % (url, text)
    return u'''<a href="http://www.fuwo.com%s" class="text-purple" target="_blank"><span class="Eblue">%s</span></a>''' % (url, text)

def send_message(category, send_user, recv_user, content):
    '''发送站内消息'''
    try:
        msg = Message.objects.send_message(category, send_user, recv_user, content)
        return 'SUCCESS', msg
    except:
        return 'FAILED', None

def send_system_message(recv_user, content):
    """ 发送系统消息 """
    # 更新用户消息数
    try:
        msg = Message.objects.send_system_message(recv_user, content)
        return 'SUCCESS', msg
    except:
        return 'FAILED', None
    
def get_message(category, recv_user_id):
    return Message.objects.get_message(category, recv_user_id)

def get_unreaded_message(category, recv_user_id):
    return Message.objects.get_unreaded_message(category, recv_user_id)

def get_readed_message(category, recv_user_id):
    return Message.objects.get_readed_message(category, recv_user_id)
    

def send_html_email(subject, to_emails, template_name, dictionary, header_from=u'Fuwo.com'):
    '''
    function: 发送html格式邮件
    subject: 邮件主题
    to_emails: 收件邮箱列表
    template: 邮件模版
    context: 模版上下文替换
    '''

    email_body = render_to_string(template_name, dictionary)
    connection = get_connection(backend='common.core.mail.backends.PublicEmailBackend')
    email = DJEmailMessage(subject=subject,
                         body=email_body,
                         from_email=settings.PUBLIC_EMAIL_HOST_USER,
                         to=to_emails,
                         connection=connection,
                         headers={'From': '%s <%s>' % (header_from, settings.PUBLIC_EMAIL_HOST_USER)})
    email.content_subtype = 'html'
    
    try:
        email.send()
        for to_email in to_emails:
            EmailMessage.objects.create(email=to_email, content=email_body, is_pushed=True)
        return True
    except Exception, e:
        for to_email in to_emails:
            EmailMessage.objects.create(email=to_email, content=email_body, is_pushed=False)
        if e[0] == 550 and e[1].startswith('RP:TRC'):
            return False
        return False

def send_sms_message(mobile, sms_content, recv_user=None, simplex=True, sendtime=''):
    '''
    function: 发短信 
    mobile: 手机号
    sms_content: 短信内容
    simplex:只发一条短信长度的内容
    ps: 当短信内容>70汉字的时候会算作2条以上的短信，所以没有特殊情况的话先预检内容长度。
    return：resp 提交结果
        resp[0] 状态值：
        -1    账号不存在
        -2    密码错误
        -3    账号被锁
        -4    账号余额为0
        -5    短信内容含有关键字
        -6    标示号taskId有误
        -7    短信内容前没加后缀（见注释2）
        -8    提交的短信号码低于账号最低配置
        -9    短信发送量超出当日规定数量
        0    短信发送成功
        1    其他错误
        2    账号信息有误
        3    短信内容或号码为空
        4    账号余额不够发送当前短信
        5    发送短信过程中出错
        ###### 自定义错误
        6    手机号码错误
        20    接口调用失败，连接被重置
    '''
    # 去掉链接
    sms_content = sms_content.replace('www.fuwo.com', '')
    # 短信内容控制在一条, 签名【爱福窝】占用5个长度
    if simplex:
        sms_content = sms_content[:65]
    if str(mobile).__len__() != 11:
        return ['6', u'手机号码错误']
    
    req_url = settings.MESSAGE_SMS_SEND_API
    task_id = '_'.join([settings.MESSAGE_SMS_ACCOUNT,
                        datetime.datetime.strftime(datetime.datetime.now(), "%Y%m%d%H%M%S"),
                        'http',
                        ''.join(random.sample('0123456789', 6))])
    
    params = {
        "account":settings.MESSAGE_SMS_ACCOUNT,
        "password":settings.MESSAGE_SMS_PASSWORD,
        "content":'%s' % (sms_content.encode('utf-8').replace('&', '＆')),
        "phonelist":mobile,
        "taskId":task_id,
        "sendtime":sendtime
    }
    params = urllib.urlencode(params)
    # 调用短信接口
    try:
        req = urllib2.urlopen('%s?%s' % (req_url, params))
        resp = req.read()
        req.close()
    except urllib2.URLError:
        return ['20', u'接口调用失败，连接被重置']
    # 解析返回结果
    resp = resp.split(",") if resp[0] == "0" else resp.split("<br/>")
    # 发送状态
    is_pushed = True if resp[0] == "0" else False
    # 余额不足的邮件通知
    if resp[0] == "-4":
        send_admin_email.delay(u"手机短信接口错误", u"账号余额为0")
    if resp[0] == "4":
        send_admin_email.delay(u"手机短信接口错误", u"账号余额不够发送当前短信")
    # 记录短信发送信息
    kwargs = {"mobile":mobile, "content":sms_content, "is_pushed":is_pushed}
    if recv_user:
        kwargs['recv_user'] = recv_user
    MobileMessage.objects.create(**kwargs)
    return resp


@task
def send_cron_email(subject, content, header_from=u'Fuwo.com'):
    u'''发送cron执行结果的email'''
    
    try:
        email = DJEmailMessage(subject=subject,
                               body=content,
                               from_email=settings.ADMIN_EMAIL_HOST_USER,
                               to=[admin[1] for admin in settings.ADMINS],
                               headers={'From': '%s <%s>' % (header_from, settings.ADMIN_EMAIL_HOST_USER)})
        email.content_subtype = 'html'
        email.send()
    except:
        logger.error('Celery task got exception.',
                    exc_info=sys.exc_info(),
                    extra={
                        'status_code': 400,
                    }
                )
    
@task
def send_admin_email(subject, content, header_from=u'Fuwo.com',
                      mail_from=settings.ADMIN_EMAIL_HOST_USER,
                      mail_to=[admin[1] for admin in settings.ADMINS]):
    """发送管理邮件"""
    try:
        email = DJEmailMessage(subject=subject,
                               body=content,
                               from_email=mail_from,
                               to=mail_to,
                               headers={'From': '%s <%s>' % (header_from, mail_from)})
        email.content_subtype = 'html'
        email.send()
    except:
        logger.error('Celery task got exception.',
                    exc_info=sys.exc_info(),
                    extra={
                        'status_code': 400,
                    }
                )


def send_validate_message(to_who, ip):
        '''判断手机号和邮箱，发送验证码'''
        #生成 验证码
        seeds = u'''0123456789'''
        random_str = u''.join([random.choice(seeds) for i in range(6)])
        telregex = r'^[1][3-8]\d{9}$'
        emailregex = r'^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9])+\.)+([a-zA-Z0-9]{2,4})+$'
        emailsended = smssended = False
        if re.match(telregex, to_who):
            category = 0
            content = u'验证码%s，如非本人操作，请忽略本信息。www.fuwo.com' % random_str
            resp = send_sms_message(to_who, content)
            smssended = True if resp[0] == "0" else False
            ValidateMessage.objects.create(category=category, sendto=to_who, validatecode=random_str, is_pushed=smssended, ip=ip)
        elif re.match(emailregex, to_who):
            category = 1
            email_template = 'account/validate_email.html'
            dictionary = {
                        'email': to_who,
                        'validate_code': random_str,
                        'change_password_url': '',
                    }
            emailsended = send_html_email(u'您的验证码', [to_who], email_template, dictionary)
            ValidateMessage.objects.create(category=category, sendto=to_who, validatecode=random_str, is_pushed=emailsended, ip=ip)
        else:
            return False
        return True
